package com.common.util.utils;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Environment;
import android.os.SystemClock;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @文件名称：CrashHandler.java
 * @文件作者：link
 * @文件描述：捕获crash日志
 * @版本： 1.0.0
 * @创建时间：2017-11-09 10:30
 * @修改历史：2017-11-09 10:30
 */

public class CrashHandler implements Thread.UncaughtExceptionHandler {

    //日志目录
    private static final String LOG_DIR = Environment.getExternalStorageDirectory().getPath() + File.separator ;
    //日志文件名
    private static final String LOG_NAME = "crash_";
    //日志后缀
    private static final String LOG_NAME_SUFFIX = ".trace";

    private Context mContext;
    private static CrashHandler mInstance;

    private CrashHandler() {

    }

    public void init(Context context) {
        this.mContext = context.getApplicationContext();
        //设置异常捕获
        Thread.setDefaultUncaughtExceptionHandler(this);
    }

    public static CrashHandler getInstance() {
        if (mInstance == null) {
            synchronized (CrashHandler.class) {
                if (mInstance == null) {
                    mInstance = new CrashHandler();
                }
            }
        }
        return mInstance;
    }

    /**
     * 捕获异常回调
     * @param thread    当前线程
     * @param ex        异常信息
     */
    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        //导出异常信息到SD卡
        dumpExceptionToSDCard(ex);
        //上传异常信息到服务器
        uploadExceptionToServer(ex);
        //延时1秒杀死进程
        killProcess();
    }

    /**
     * 导出异常信息到SDCard
     * @param ex
     */
    private void dumpExceptionToSDCard(Throwable ex) {
        // 判断是否可读写
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            return;
        }

        String logDir = LOG_DIR + mContext.getPackageName() + "/crash_log/";
        File dir = new File(logDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        // 获取当前时间
        long currentTime = System.currentTimeMillis();
        String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(currentTime));
        // 以当前时间创建log文件
        File file = new File(logDir + LOG_NAME + time + LOG_NAME_SUFFIX);
        try {
            PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(file)));
            // 导出手机信息和异常信息
            PackageManager pm = mContext.getPackageManager();
            PackageInfo packageInfo = pm.getPackageInfo(mContext.getPackageName(), PackageManager.GET_ACTIVITIES);
            pw.println("发生异常时间:" + time);
            pw.println("应用版本:" + packageInfo.versionName);
            pw.println("应用版本号:" + packageInfo.versionCode);
            pw.println("android版本号:" + Build.VERSION.RELEASE);
            pw.println("android版本API:" + Build.VERSION.SDK_INT);
            pw.println("手机制造商:" + Build.MANUFACTURER);
            pw.println("手机型号:" + Build.MODEL);
            ex.printStackTrace(pw);
            // 关闭输出流
            pw.close();
        } catch (Exception e) {

        }

    }

    /**
     * 上传异常信息到服务器
     * @param ex
     */
    private void uploadExceptionToServer(Throwable ex) {
//        Error error = new Error(ex.getMessage());
//        error.save(new SaveListener<String>() {
//            @Override
//            public void done(String objectId, BmobException e) {
//
//            }
//        });
    }

    /**
     * 退出进程
     */
    private void killProcess() {
        SystemClock.sleep(1000);
        System.exit(1);
        android.os.Process.killProcess(android.os.Process.myPid());
    }
}
